const Banner = require('../models/bannerModel');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'server/public/images/banners/');
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 5 * 1024 * 1024 // 限制5MB
    },
    fileFilter: function (req, file, cb) {
        // 只接受图片文件
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif|svg)$/)) {
            return cb(new Error('只允许上传图片文件！'), false);
        }
        cb(null, true);
    }
});

// 获取所有轮播图
const getBanners = async (req, res) => {
    try {
        const banners = await Banner.find({ isActive: true })
            .sort({ order: 1, createdAt: -1 });
        res.json({
            success: true,
            data: {
                banners
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

// 添加轮播图
const addBanner = async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({
                success: false,
                message: '请上传图片'
            });
        }

        const banner = new Banner({
            imageUrl: `/images/banners/${req.file.filename}`,
            link: req.body.link,
            order: req.body.order || 0,
            isActive: req.body.isActive !== 'false'
        });

        const newBanner = await banner.save();
        res.status(201).json({
            success: true,
            data: {
                banner: newBanner
            }
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
};

// 更新轮播图
const updateBanner = async (req, res) => {
    try {
        const banner = await Banner.findById(req.params.id);
        if (!banner) {
            return res.status(404).json({
                success: false,
                message: '轮播图不存在'
            });
        }

        // 如果有新图片上传
        if (req.file) {
            // 删除旧图片
            const oldImagePath = path.join(__dirname, '../public', banner.imageUrl);
            if (fs.existsSync(oldImagePath)) {
                fs.unlinkSync(oldImagePath);
            }
            // 更新图片URL
            banner.imageUrl = `/images/banners/${req.file.filename}`;
        }

        // 更新其他字段
        if (req.body.link) banner.link = req.body.link;
        if (req.body.order !== undefined) banner.order = req.body.order;
        if (req.body.isActive !== undefined) banner.isActive = req.body.isActive === 'true';

        const updatedBanner = await banner.save();
        res.json({
            success: true,
            data: {
                banner: updatedBanner
            }
        });
    } catch (error) {
        res.status(400).json({
            success: false,
            message: error.message
        });
    }
};

// 删除轮播图
const deleteBanner = async (req, res) => {
    try {
        const banner = await Banner.findById(req.params.id);
        if (!banner) {
            return res.status(404).json({
                success: false,
                message: '轮播图不存在'
            });
        }

        // 从文件系统中删除图片
        const imagePath = path.join(__dirname, '../public', banner.imageUrl);
        if (fs.existsSync(imagePath)) {
            fs.unlinkSync(imagePath);
        }

        // 从数据库中删除记录
        await banner.deleteOne();
        res.json({
            success: true,
            data: {
                message: '轮播图已删除'
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: error.message
        });
    }
};

module.exports = {
    getBanners,
    addBanner,
    updateBanner,
    deleteBanner,
    upload
}; 